package com.ia2014.tp.portal2.ejb.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ia2014.tp.portal2.ejb.ConfigRemote;
import com.ia2014.tp.portal2.ejb.controller.ConfigController;
import com.ia2014.tp.portal2.exception.ConfigException;

@WebServlet("/eliminarModulo")
public class EliminarModuloServlet extends HttpServlet{
	private static final long serialVersionUID = 1157965236578767676L;
	private static final String MODULO_DEPOSITO 	= "deposito";
	private static final String MODULO_DESPACHO 	= "despacho";
	private static final String MODULO_LOGISTICA 	= "logistica";
	private static final String MODULO_PORTAL 		= "portal";
	
	@EJB
	private ConfigRemote config;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String moduloABorrar = req.getParameter("modulo");
		String idModulo = req.getParameter("moduloId");
		String redirect = req.getContextPath() + "/faces/viewModulos.xhtml";
		Integer idModuloInteger = 0;
		ConfigController configController = (ConfigController) req.getSession().getAttribute("configController");
		
		if (idModulo != null && !idModulo.trim().isEmpty()){
			try {
				idModuloInteger = Integer.parseInt(idModulo);
			} catch (NumberFormatException e) {
				idModuloInteger = 0;
			}
			
			if (MODULO_DEPOSITO.equals(moduloABorrar)){
				try {
					this.config.eliminarDeposito(idModuloInteger);
					if (configController != null){
						configController.removeDepositoDTO(idModuloInteger);
					}
					
				} catch (ConfigException e) {
					e.printStackTrace();
				}
			}else if(MODULO_DESPACHO.equals(moduloABorrar)){
				try {
					this.config.eliminarDespacho(idModuloInteger);
					if (configController!=null){
						configController.removeDespachoDTO(idModuloInteger);
					}
				} catch (ConfigException e) {
					e.printStackTrace();
				}
			}else if(MODULO_LOGISTICA.equals(moduloABorrar)){
				try {
					this.config.eliminarLogistica(idModuloInteger);
					if (configController!=null){
						configController.removeLogisticaDTO(idModuloInteger);
					}
				} catch (ConfigException e) {
					e.printStackTrace();
				}	
			}else if(MODULO_PORTAL.equals(moduloABorrar)){
				try {
					this.config.eliminarPortal(idModuloInteger);
					if(configController!=null){
						configController.removePortalDTO(idModuloInteger);
					}
				} catch (ConfigException e) {
					e.printStackTrace();
				}	
			}
		}

		resp.sendRedirect(redirect);
	}	
}
